<?php
Zend_Loader::loadClass("Application_Ajax_Server_Function");
Zend_Loader::loadClass("ConstructionsMaterials");
class GetConstructionDetailsById extends Application_Ajax_Server_Function
{
	public function call() {
		$id = (int) $this->_params['id'];
		Zend_Loader::loadClass('Constructions');
		$costruzioni = new Constructions();

		$cm = new ConstructionsMaterials();
		$recordSet = $costruzioni->find($id);
		$costruzione = $recordSet->current();
		$props_physical = $costruzione->findDependentRowset("ConstructionPropsPhysical");
		$props_thermal = $costruzione->findDependentRowset("ConstructionPropsThermal");
		$constructions_materials = $costruzione->findDependentRowset("ConstructionsMaterials");
		$materials = $costruzione->findManyToManyRowset("Materials", "ConstructionsMaterials");

		$result = array(
			$costruzione->toArray(),
			'category' => $costruzione->findParentRow('ConstructionCategories')->name,
			'props' => array (
					'physical' => $props_physical->toArray(),
					'thermal'  => $props_thermal->toArray(),
			),
			'materials' => array(),	// Riempito sotto
			'prev' => 0,			// Riempito sotto
			'next' => 0				// Riempito sotto
		);
	
		$layers = 0;
		foreach ($materials as $k => $m) {
			if ($constructions_materials[$k]->thickness != 0) {
				$layers++;
				$result['materials'][$k] = $m->toArray();
				$result['materials'][$k]['layer'] = $constructions_materials[$k]->layer;
				$result['materials'][$k]['thickness'] = $constructions_materials[$k]->thickness;
				$result['materials'][$k]['props']['physical'] = $m->findDependentRowset("MaterialPropsPhysical")->toArray();
				$result['materials'][$k]['props']['thermal'] = $m->findDependentRowset("MaterialPropsThermal")->toArray();
				$result['materials'][$k]['props']['ecarbon'] = $m->findDependentRowset("MaterialPropsEcarbon")->toArray();
			}
		}
		$result['layers'] = $layers;
		function cmp($a, $b) {
			if ($a['layer'] == $b['layer']) return 0;
			return ($a['layer'] > $b['layer']) ? 1 : -1;
		}
		usort ($result['materials'], "cmp");

		// Build prev/next circular array
		if (!$costruzione->id_category) {
			$recordSet = $costruzioni->select()->from($costruzioni, array("id"))
			->where("id_category is null")
			->where("status > ?", 0)
			->order("name");
		} else {
			$recordSet = $costruzioni->select()->from($costruzioni, array("id"))
			->where("id_category = ?", $costruzione->id_category)
			->where("status > ?", 0)
			->order("name");
		}

		$ids = $costruzioni->fetchAll($recordSet)->toArray();
		foreach ($ids as $k => $v)
		{
			if($v["id"] == $id)
			{
				if (isset($ids[$k-1]))
					$prev = $ids[$k-1];
				else
					$prev = end($ids);
				if (isset($ids[$k+1]))
					$next = $ids[$k+1];
				else
					$next = $ids[0];
			}
		}
		$result['prev'] = $prev["id"];
		$result['next'] = $next["id"];
		
		return $result;
	}
}